package soft_pattern.design_pattern.dp_3_behavioral;

/* 观察者模式 */

import java.util.ArrayList;
import java.util.List;

// 主题接口, 观察者订阅的方式
interface Subject {
    void register(Observer observer);

    void remove(Observer observer);

    void notifyObserver();
}

// 具体主题类, 实现了主题接口
class SubjectImpl implements Subject {
    private List<Observer> observerList = new ArrayList<>();
    private String state;

    @Override
    public void register(Observer observer) {
        observerList.add(observer);
    }

    @Override
    public void remove(Observer observer) {
        observerList.remove(observer);
    }

    @Override
    public void notifyObserver() {
        observerList.forEach(observer -> observer.receiveNotify(state));
    }

    public void setState(String state) {
        this.state = state;
        notifyObserver();
    }
}

// 观察者接口, 定义了观察者接收通知的方式
interface Observer {
    void receiveNotify(String state);
}

// 具体观察者类, 实现了观察者接口
class ConcreteObserver implements Observer {
    private String name;

    public ConcreteObserver(String name) {
        this.name = name;
    }

    @Override
    public void receiveNotify(String state) {
        System.out.println(name + " receive update with new state: " + state);
    }
}


public class ObserverPattern {
    public static void main(String[] args) {
        // create subject
        SubjectImpl subject = new SubjectImpl();

        // register observer
        subject.register(new ConcreteObserver("observer1"));
        subject.register(new ConcreteObserver("observer2"));

        // 改变主题状态, 通知观察者
        subject.setState("change");
    }
}